package com.wasin.server.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author wasin
 * @description: 日志aop
 * date 2021-02-14
 */
@Component
@Aspect
public class LogAspect {
    private static final Log LOG = LogFactory.getLog(LogAspect.class);

    /**
     * 定义一个切入点 只拦截controller.
     * 解释下：
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(* com.wasin.server.controller..*.*(..))")
    public void logPointcut() {

    }

    @Before("logPointcut()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        LOG.info("请求方法:"+request.getRequestURI()+"开始-------------------");
        LOG.info("参数: " + Arrays.toString(joinPoint.getArgs()));
        //LOG.info("接口名称 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //LOG.info("用户IP:" + request.getRemoteAddr());
    }

    //配置后置通知,使用在方法aspect()上注册的切入点
    @After("logPointcut()")
    public void After(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        LOG.info("请求方法:"+request.getRequestURI()+"结束-------------------");
        LOG.info("参数: " + Arrays.toString(joinPoint.getArgs()));
        //LOG.info("接口名称 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
       // LOG.info("用户IP:" + request.getRemoteAddr());
    }

}
